using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Serialization;

namespace Ltf.Remoting.Settings
{
	public class SettingsFactory
	{

		private static string settingsPath
		{
			get
			{
				string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
				string lizardAppData = Path.Combine(appData, "Lizard");
				if (!Directory.Exists(lizardAppData))
					Directory.CreateDirectory(lizardAppData);
				return lizardAppData;
			}

		}

		public static ISettings LoadSettings(string configName, Type type)
		{
			ISettings settings = null;
			string fileName = Path.Combine(settingsPath, configName);

			if (File.Exists(fileName))
			{
				using (FileStream isfs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
				{
					XmlSerializer xs = new XmlSerializer(type);
					settings = (ISettings)xs.Deserialize(isfs);
				}
			}
			else
			{
				try
				{
					settings = (ISettings)type.GetConstructor(new Type[] { }).Invoke(new object[] { });
				}
				catch { }
			}
			return settings;
		}

		public static void SaveSettings(string configName, ISettings settings)
		{
			using (FileStream isfs = new FileStream(Path.Combine(settingsPath, configName), FileMode.Create, FileAccess.Write))
			{

				XmlSerializer xs = new XmlSerializer(settings.GetType());
				xs.Serialize(isfs, settings);
			}


		}
	}
}
